﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SongClassifier
{
    public class FreqDeviList
    {
        SortedList<double, int> list = new SortedList<double, int>();

        public void Add(double devi, int freq)
        {
            list.Add(devi, freq);
        }

        public KeyValuePair<double,int> GetFirst()
        {
            return list.First();
        }

        public KeyValuePair<double, int> GetLast()
        {
            return list.Last();
        }

        public static double CalculateDevi(double[] data_r, double[] data_i)
        {
            double threshold = 0;
            double[] value = new double[data_r.Length];
            for (int i = 0; i < data_r.Length; i++)
            {
                value[i] = Math.Sqrt(data_r[i] * data_r[i] + data_i[i] * data_i[i]);
                if (value[i] > threshold)
                    threshold = value[i];
            }
            threshold /= 3;
            List<double> wavLenList = new List<double>();
            bool higherThanLeft, higherThanRight;
            int lastClimax = 0;
            double wavLenSum = 0;
            for (int cur = 0; cur < value.Length; cur++)
            {
                higherThanLeft = higherThanRight = false;
                int i = cur;
                while (--i >= 0 && value[cur] == value[i]) ;
                if (i < 0 || value[i]<value[cur])
                    higherThanLeft = true;
               
                i = cur;
                while (++i < value.Length && value[cur] == value[i]) ;
                if (i == value.Length || value[i] < value[cur])
                    higherThanRight = true;

                if (higherThanLeft && higherThanRight && value[cur]>threshold)
                {
                    wavLenList.Add(cur - lastClimax);
                    wavLenSum += (cur - lastClimax);
                    lastClimax = cur;
                }
            }
            double wavLenAvg = wavLenSum / wavLenList.Count;
            double devi = 0;
            foreach (double wavLen in wavLenList)
            {
                devi += (wavLen - wavLenAvg) * (wavLen - wavLenAvg);
            }
            return devi;
        }
    }
}
